package server.main.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import server.main.pojo.Account;
import server.main.service.CaptchaService;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @auther MingHsZzz
 * @Date 2022/9/8  14:01
 * @project main
 * @description
 */

@Service("CaptchaService")
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    RedisTemplate redisTemplate;


    private final char[] chars = {
            '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    // 字符数量
    private final int SIZE = 4;
    // 干扰线数量
    private final int LINES = 4;
    // 宽度
    private final int WIDTH = 83;
    // 高度
    private final int HEIGHT = 40;
    // 字体大小
    private final int FONT_SIZE = 30;

    private int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    /**
     * 生成随机验证码及图片
     * Object[0]：验证码字符串；
     * Object[1]：验证码图片。
     */
    public Object[] createImage() {
        StringBuffer sb = new StringBuffer();
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        for (int i = 0; i < SIZE; i++) {
            // 取随机字符索引
            int n = ran.nextInt(chars.length);
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 设置字体大小
            graphic.setFont(new Font(
                    null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            // 画字符
            graphic.drawString(
                    chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3);
            // 记录字符
            sb.append(chars[n]);
        }
        // 6.画干扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                    ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图片
        return new Object[]{sb.toString(), image};
    }

    /**
     * 随机取色
     */
    public Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }


    public List<String> getVerifyCode() {
        List<String> goal = new ArrayList<>();
        ByteArrayOutputStream outputStream = null;
        try {
            Object[] objects = createImage();
            // 得到图片
            BufferedImage image = (BufferedImage) objects[1];
            // 得到验证码
            String valueCode = objects[0].toString().toLowerCase();
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            // base64将输出流程的byte[] 进行转码
            String pic = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            goal.add(valueCode);
            goal.add(pic);

        } catch (Exception e) {
//            log.error("生成验证码错误", e);
//            requestResult.setCode(ResultTypeEnum.FU_EXC_9702.getCode());
//            requestResult.setMessage(ResultTypeEnum.FU_EXC_9702.getDesc());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception ex) {
//                log.error("关闭流错误", ex);
            }
        }
        return goal;
    }


    @Override
    public String getCaptcha() {
        List<String> verifyCode = getVerifyCode();


        String captcha = verifyCode.get(0).toString().toLowerCase();
        System.out.println(captcha);

        redisTemplate.opsForValue().setIfAbsent("captcha" + captcha,"1",10 * 60L,TimeUnit.SECONDS);

//        System.out.println(redisTemplate.opsForValue().get("captcha:" + captcha));


        return verifyCode.get(1);
    }


    @Override
    public Boolean isLegal(String captcha) {
        System.out.println(captcha);

        if (captcha == null) {
            return false;
        }

        String key = "captcha" + captcha.toLowerCase();
        System.out.println(redisTemplate.opsForValue().get(key));
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj != null) {
            redisTemplate.delete(key);
        }

        return obj != null;
    }
}
